package com.ytlz.dmcs.model.system.view;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ytlz.dmcs.common.UserInfo;
import com.ytlz.dmcs.config.SystemConfiguration;
import com.ytlz.dmcs.model.system.dao.UserDao;
import com.ytlz.dmcs.model.system.entity.SysUser;
import com.ytlz.dmcs.model.system.service.MenuService;

@Controller
@RequestMapping("/")
public class IndexView {
	
	@Autowired
	private SystemConfiguration config;

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private MenuService menuService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(method= {RequestMethod.POST,RequestMethod.GET})
	public String index(HttpServletRequest request,Model model) {
		
		model.addAttribute("apptitle", config.getApplicationName());
		model.addAttribute("appcopyright", config.getCopyright());
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		System.out.println("login username : "+userDetails.getUsername());
		
		SysUser userObj = userDao.findByUsername(userDetails.getUsername());
		
		Iterator<SimpleGrantedAuthority> rolsIterator = (Iterator<SimpleGrantedAuthority>) userDetails.getAuthorities().iterator();
		while (rolsIterator.hasNext()) {
			SimpleGrantedAuthority grantedAuthority = (SimpleGrantedAuthority) rolsIterator.next();
			System.out.println("login rolename : "+grantedAuthority.getAuthority());
			
		}
		model.addAttribute("menulist", getMenus());
		
		model.addAttribute("userinfo", new UserInfo(userDetails.getUsername(),userObj.getDisplayname()));
		
		return "index";
	}
	
	private List<Map<String, Object>> getMenus(){

		return menuService.getAllMenus();
	}
}
